package net.jueb.object.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ObjectServer {
	
	public void start(int port)
	{
		NioEventLoopGroup boss=new NioEventLoopGroup();
		NioEventLoopGroup worker=new NioEventLoopGroup();
		ServerBootstrap sbt=new ServerBootstrap();
		sbt.group(boss, worker);
		sbt.option(ChannelOption.SO_BACKLOG, 65536);
		sbt.channel(NioServerSocketChannel.class);
		sbt.handler(new LoggingHandler(LogLevel.DEBUG));
		sbt.childHandler(new ChannelInitializer<SocketChannel>(){

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				/**
				 * Object编码解码器自带tcp分包拆包功能
				 */
				ClassResolver cr=ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader());
				ObjectDecoder od=new ObjectDecoder(1024*1024,cr);
				sc.pipeline().addLast(od);//加入对象解码器
				sc.pipeline().addLast(new ObjectEncoder());//加入对象编码器
				sc.pipeline().addLast(new ObjectServerHandler());
			}});
		try {
			Channel channel=sbt.bind(port).sync().channel();
			System.out.println("服务端启动成功，端口："+port);
			channel.closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) {
		new ObjectServer().start(80);
	}
}
